<script setup lang="ts">
import { onMounted, onBeforeUnmount } from 'vue'
import { createWebSocket, closeWebSocket, registerMessageListener, removeMessageListener } from './api/ws.js'

//从localstorage中拿到用户的id
const userId = Number(localStorage.getItem("userId"))
onMounted(() => {
  if (userId) {
    // 登录后创建 WebSocket 连接
    createWebSocket(userId)

    // 注册全局消息监听
    const handleMessage = (msg) => {
      console.log('📩 收到来自服务器的消息：', msg)
      // 你可以在这里用全局通知提示，例如：
      // ElNotification({ title: msg.title, message: msg.content, type: 'info' })
    }

    registerMessageListener(handleMessage)

    // 页面关闭或刷新时，主动关闭连接
    window.addEventListener('beforeunload', () => {
      closeWebSocket()
    })

    // 离开应用时取消监听（防止内存泄漏）
    onBeforeUnmount(() => {
      removeMessageListener(handleMessage)
      closeWebSocket()
    })
  }
})

</script>

<template>

  
  <div>
    <router-view/>
  </div>
</template>

<style scoped>
</style>
